package com.motong.gongdan.util;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.util.IoUtils;
import com.google.common.collect.Lists;
import com.motong.gongdan.config.auth.LoginException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.*;

/**
 * @author:fff
 * @time:2022/6/21
 */
public class EasyExcelImportUtils {
    public static List<Map<String,String>> parseExcelToData(byte[] stream, Integer parseRowNumber) {
        EasyExcelListener readListener = new EasyExcelListener();
        EasyExcelFactory.read(new ByteArrayInputStream(stream)).registerReadListener(readListener).headRowNumber(parseRowNumber).sheet(0).doRead();
        List<Map<Integer, String>> headList = readListener.getHeadList();
        if(CollectionUtils.isEmpty(headList)){
//            throw new RuntimeException("Excel表头不能为空");
            throw new LoginException("500","Excel表头不能为空");
//            return null;
        }
        List<Map<Integer, String>> dataList = readListener.getDataList();
        if(CollectionUtils.isEmpty(dataList)){
//            throw new RuntimeException("Excel数据内容不能为空");
//            throw new LoginException("500","Excel数据内容不能为空");
            return null;
//            throw new LoginException("200","导入完成");
//            return null;
        }
        //获取头部,取最后一次解析的列头数据
        Map<Integer, String> excelHeadIdxNameMap = headList.get(headList.size() -1);
        //封装数据体
        List<Map<String,String>> excelDataList = Lists.newArrayList();
        for (Map<Integer, String> dataRow : dataList) {
            Map<String,String> rowData = new LinkedHashMap<>();
            excelHeadIdxNameMap.entrySet().forEach(columnHead -> {
                rowData.put(columnHead.getValue(), dataRow.get(columnHead.getKey()));
            });
            excelDataList.add(rowData);
        }
        return excelDataList;
    }

    /**
     * 返回导入的所有数据
     * [file]
     * @return {@link List< Map< String, String>>}
     * @throws
     */
    public static List<Map<String,String>> makeData(MultipartFile file){
        InputStream inputStream = null;//转换成输入流
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] stream = new byte[0];
        try {
            stream = IoUtils.toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(stream == null || stream.length == 0){
            return null;
        }
        List<Map<String,String>> dataList = parseExcelToData(stream, 1);//从动态获取全部列和数据体，默认从第一行开始解析数据
        try {
            if(inputStream != null){
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataList;
    }


    public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int)file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }


    public static List<Map<String,String>> parseExcelToData(byte[] stream, Integer parseRowNumber,String firstColumnName) {
        EasyExcelListener readListener = new EasyExcelListener();
        EasyExcelFactory.read(new ByteArrayInputStream(stream)).registerReadListener(readListener).headRowNumber(parseRowNumber).sheet(0).doRead();
        List<Map<Integer, String>> headList = readListener.getHeadList();
        if(CollectionUtils.isEmpty(headList)){
            throw new LoginException("500","Excel表头不能为空");
        }
        List<Map<Integer, String>> dataList = readListener.getDataList();
        //获取头部,取最后一次解析的列头数据
        Map<Integer, String> excelHeadIdxNameMap = headList.get(headList.size() -1);
        if (StringUtils.hasLength(firstColumnName)&&!excelHeadIdxNameMap.getOrDefault(0,"").equals(firstColumnName)){
            throw new LoginException("500","模板不匹配");
        }
        if(CollectionUtils.isEmpty(dataList)){
            return null;
        }
        //封装数据体
        List<Map<String,String>> excelDataList = Lists.newArrayList();
        for (Map<Integer, String> dataRow : dataList) {
            Map<String,String> rowData = new LinkedHashMap<>();
            excelHeadIdxNameMap.forEach((key, value) -> rowData.put(value, dataRow.get(key)));
            excelDataList.add(rowData);
        }
        return excelDataList;
    }




    /**
     * 文件导入测试
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        File f = new File("/Users/fff/Downloads/导入工单模版.xlsx");
        MultipartFile file = getMultipartFile(f);
//        FileInputStream inputStream = new FileInputStream(new File("/Users/fff/Downloads/导入工单模版.xlsx"));
        byte[] stream = IoUtils.toByteArray(file.getInputStream());
        List<Map<String,String>> dataList = parseExcelToData(stream, 2);//动态获取全部列和数据体，默认从第一行开始解析数据
        List<String> objects = new ArrayList<>();
        for (Map<String, String> s : dataList) {
//            List<String> stringList = new ArrayList<>(s.keySet());
//            for(int i=0;i<stringList.size();i++){
//                System.out.println("表头："+stringList.get(i)+"===="+"值："+s.get(stringList.get(i)));
//            }
            System.out.println(s.values());
        }
//        System.out.println("属性项:"+objects);
//        System.out.println("值:"+dataList);
    }
}
